dfs and similar graphs greedy *2000

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
#include<unordered_map>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define Analog ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long
#define endl "\n"
#define fix(a,k) ((a%k)+k)%k
using namespace __gnu_pbds;

#define ordered_set tree<int, null_type,less_equal<int>, rb_tree_tag,tree_order_statistics_node_update>

using namespace std;
void File()
{
#ifndef ONLINE_JUDGE
    freopen("file.txt", "r", stdin);
    freopen("o.txt", "w", stdout);
#endif
}
ll gcd(ll a, ll b)
{
    return b == 0 ? a : gcd(b, a % b);
}
struct edge
{
    ll node, mn, cost;
};
struct cmp
{
    bool operator()(edge a, edge b)
    {
        return a.cost > b.cost;
    }
};
vector<int>adj[5001];
int vis[5001];
vector<int>topo;
void dfs(int node)
{
    vis[node]=1;
    for(auto&ch:adj[node])
    {
        if (!vis[ch])
            dfs(ch);
    }
    topo.push_back(node);
}
int ans=0;
set<int>notvisited;
bool sony=0;
void dfs2(int node)
{
    vis[node]=1;
    if (notvisited.find(node)!=notvisited.end() and !sony)
        ans++,sony=1;
    for(auto&i:adj[node])
    {
        if (!vis[i])
        {
            dfs2(i);
        }
    }
}
int main()
{
    Analog
    File();
    int t = 1;
    //cin >> t;
    int tst=1;
    while(t--)
    {
        int n,m,s;
        cin>>n>>m>>s;
        for(int i=1; i<=m; i++)
        {
            int u,v;
            cin>>u>>v;
            adj[u].push_back(v);
        }
        dfs(s);
        for(int i=1;i<=n;i++)
        {
            if (!vis[i])
            {
                notvisited.insert(i);
            }
        }
        memset(vis,0,sizeof vis);
        for(int i=1;i<=n;i++)
        {
            if (!vis[i])
                dfs(i);
        }
        reverse(topo.begin(),topo.end());
        memset(vis,0,sizeof vis);
        for(int i=0;i<topo.size();i++)
        {
            if (!vis[topo[i]])
            {
                sony=0;
                dfs2(topo[i]);
            }
        }
        cout<<ans;


    }
}

     				 		 	 				    		 		  	


Comments

Submit
0 Comments
More Questions

515C - Drazil and Factorial
1151E - Number of Components
1151F - Sonya and Informatics
556A - Case of the Zeros and Ones
867A - Between the Offices
1569A - Balanced Substring
260A - Adding Digits
1698C - 3SUM Closure
1029B - Creating the Contest
1421A - XORwice
1029A - Many Equal Substrings
1675D - Vertical Paths
1271C - Shawarma Tent
805A - Fake NP
1163A - Eating Soup
787A - The Monster
807A - Is it rated
1096A - Find Divisible
1430C - Numbers on Whiteboard
1697B - Promo
208D - Prizes Prizes more Prizes
659A - Round House
1492C - Maximum width
171B - Star
1512B - Almost Rectangle
831B - Keyboard Layouts
814A - An abandoned sentiment from past
268C - Beautiful Sets of Points
1391C - Cyclic Permutations
11A - Increasing Sequence